package cn.wolfcode.shop.filter;

import cn.wolfcode.shop.common.Result;
import cn.wolfcode.shop.feign.TokenFeignApi;
import cn.wolfcode.shop.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenRefreshFilter extends ZuulFilter{

    @Autowired
    private TokenFeignApi tokenFeignApi;

    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    public int filterOrder() {
        return 10;
    }

    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = CookieUtil.getCookie(request, CookieUtil.TOKEN_NAME);
        if(StringUtils.isEmpty(token)){
            return false;
        }else{
            return true;
        }
    }

    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        String token = CookieUtil.getCookie(request, CookieUtil.TOKEN_NAME);
        Result<Boolean> result = tokenFeignApi.refreshToken(token);
        if(result!=null && !result.hasError() && result.getData()){
            //token在redis中都刷新成功了,我们才需要重写刷新cookie时间
            CookieUtil.addCookie(response,CookieUtil.TOKEN_NAME,token,CookieUtil.TOKEN_EXPIRE_SECONDS);
        }
        return null;

    }
}
